import { _decorator, Component, Node, Sprite, SpriteFrame } from 'cc';
import { GameController } from './GameController';
const { ccclass, property } = _decorator;

@ccclass('item')
export class item extends Component {
    @property(Sprite)
    sprite: Sprite = null;
    @property(Node)
    mask: Node = null;

    ref_count: number = 0;
    childs: Array<item> = null;
    isClick: boolean = false;

    onLoad(){
        this.node.on(Node.EventType.TOUCH_END, this.onTouch, this);
    }

    init(spriteFrame: SpriteFrame, childs: Array<item>) {
        this.childs = childs;
        this.ref_count = 0;
        this.click = false;
        this.sprite.spriteFrame = spriteFrame;
        this.mask.active = false;
    }

    /**
     * 是否被点击
     */
    set click(isbool: boolean) {
        if(isbool){
            this.isClick = true;
            this.node.active = false;
            this.childs.forEach(it=>{
                it.notify(false);
            })
            GameController.getInst().selectFruit(this.sprite.spriteFrame);
        }else{
            this.isClick = false;
            this.childs.forEach(it=>{
                it.notify(true);
            })
        }
    }
    /**
     * 减少父节点引用
     */
    subRefCount() {
        this.ref_count--;
        if(this.ref_count == 0){
            this.mask.active = false;
        }
    }
    /**
     *增加父节点引用
     */
    addRefCount() {
        if(this.ref_count == 0){
            this.mask.active = true;
        }
        this.ref_count++;
    }

    /**
     * 通知
     * @param it 
     */
    notify(isInit: boolean) {
        isInit && this.addRefCount();
        !isInit && this.subRefCount();
    }

    /**
     * 触摸事件
     */
    onTouch(){
        if(this.ref_count <= 0)
            this.click = true;
    }
}


